package com.gsafety.devops.controller;

import com.gsafety.devops.entity.SqlListEntity;
import com.gsafety.devops.entity.SqlTaskEntity;
import com.gsafety.devops.page.SqlListPage;
import com.gsafety.devops.service.SqlListServiceI;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.poi.ss.usermodel.Workbook;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;

import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.ExceptionUtil;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.core.util.oConvertUtils;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.springframework.ui.ModelMap;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.jeecgframework.jwt.util.ResponseMessage;
import org.jeecgframework.jwt.util.Result;
import com.alibaba.fastjson.JSONArray;
import org.jeecgframework.web.superquery.util.SuperQueryUtil;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.http.HttpStatus;
import org.jeecgframework.core.beanvalidator.BeanValidators;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.net.URI;
import org.springframework.http.MediaType;
import org.springframework.web.util.UriComponentsBuilder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**   
 * @Title: Controller
 * @Description: SQL列表
 * @author onlineGenerator
 * @date 2018-09-26 16:12:20
 * @version V1.0   
 *
 */
@Controller
@RequestMapping("/sqlListController")
public class SqlListController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(SqlListController.class);

	@Autowired
	private SqlListServiceI sqlListService;
	@Autowired
	private SystemService systemService;

	
	
	/**
	 * SQL列表首页跳转
	 * @return
	 */
	@RequestMapping(params = "list")
	public ModelAndView index(HttpServletRequest request) {
		return new ModelAndView("com/gsafety/devops/sqlList-index");
	}
	
	
	/**
	 * SQL列表列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "mainList")
	public ModelAndView list(HttpServletRequest request) {
		return new ModelAndView("com/gsafety/devops/sqlList-list");
	}

	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(SqlListEntity sqlList,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(SqlListEntity.class, dataGrid);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, sqlList,request.getParameterMap());
		try{
			//自定义追加查询条件
			String sql = SuperQueryUtil.getComplxSuperQuerySQL(request);
			if(oConvertUtils.isNotEmpty(sql)) {
				cq.add(Restrictions.sqlRestriction(" id in ("+sql+")"));
			}
		}catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		cq.add();
		this.sqlListService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * 删除SQL列表
	 * 
	 * @return
	 */
	@RequestMapping(params = "doDel")
	@ResponseBody
	public AjaxJson doDel(SqlListEntity sqlList, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		sqlList = systemService.getEntity(SqlListEntity.class, sqlList.getId());
		String message = "SQL列表删除成功";
		try{
			sqlListService.delMain(sqlList);
			systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "SQL列表删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 批量删除SQL列表
	 * 
	 * @return
	 */
	 @RequestMapping(params = "doBatchDel")
	@ResponseBody
	public AjaxJson doBatchDel(String ids,HttpServletRequest request){
		AjaxJson j = new AjaxJson();
		String message = "SQL列表删除成功";
		try{
			for(String id:ids.split(",")){
				SqlListEntity sqlList = systemService.getEntity(SqlListEntity.class,
				id
				);
				sqlListService.delMain(sqlList);
				systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
			}
		}catch(Exception e){
			e.printStackTrace();
			message = "SQL列表删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 添加SQL列表
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public AjaxJson doAdd(SqlListEntity sqlList,SqlListPage sqlListPage, HttpServletRequest request) {
		List<SqlTaskEntity> sqlTaskList =  sqlListPage.getSqlTaskList();
		AjaxJson j = new AjaxJson();
		String message = "添加成功";
		try{
			sqlListService.addMain(sqlList, sqlTaskList);
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "SQL列表添加失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	/**
	 * 更新SQL列表
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doUpdate")
	@ResponseBody
	public AjaxJson doUpdate(SqlListEntity sqlList,SqlListPage sqlListPage, HttpServletRequest request) {
		List<SqlTaskEntity> sqlTaskList =  sqlListPage.getSqlTaskList();
		AjaxJson j = new AjaxJson();
		String message = "更新成功";
		try{
			sqlListService.updateMain(sqlList, sqlTaskList);
			systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "更新SQL列表失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * SQL列表新增页面跳转
	 * @return
	 */
	@RequestMapping(params = "goAdd")
	public ModelAndView goAdd(HttpServletRequest req) {
		//跳转新增主页面
		return new ModelAndView("com/gsafety/devops/sqlList-add");
	}
	
	/**
	 * SQL列表修改页面跳转
	 * @return
	 */
	@RequestMapping(params = "goUpdate")
	public ModelAndView goUpdate(HttpServletRequest req) {
		//跳转修改主页面
		String id = req.getParameter("id");
		req.setAttribute("mainId",id);
		req.setAttribute("load", req.getParameter("load"));
		return new ModelAndView("com/gsafety/devops/sqlList-update");
	}
	
	
	/**
	 * 订单主信息新增编辑字段页面跳转
	 * @return
	 */
	@RequestMapping(params = "mainForm")
	public ModelAndView mainForm(SqlListEntity sqlList,HttpServletRequest req) {
		if (StringUtil.isNotEmpty(sqlList.getId())) {
			sqlList = sqlListService.getEntity(SqlListEntity.class, sqlList.getId());
			req.setAttribute("sqlListPage", sqlList);
		}
		return new ModelAndView("com/gsafety/devops/page-sqlList");
	}
	
	/**
	 * 加载form列表[执行任务]
	 * 
	 * @return
	 */
	@RequestMapping(params = "sqlTaskFormList")
	public ModelAndView  sqlTaskList(SqlListEntity sqlList,HttpServletRequest req) {
	
		//===================================================================================
		//获取参数
	    Object id = sqlList.getId();
		//===================================================================================
		//查询-执行任务
	    String hql0 = "from SqlTaskEntity where 1 = 1 AND sqlId = ? ";
	    try{
	    	List<SqlTaskEntity> sqlTaskEntityList = systemService.findHql(hql0,id);
			req.setAttribute("sqlTaskList", sqlTaskEntityList);
		}catch(Exception e){
			logger.info(e.getMessage());
		}
		return new ModelAndView("com/gsafety/devops/page-sqlTask");
	}

	
	/**
	 * 行编辑保存操作
	 * @param page
	 * @return
	 */
	@RequestMapping(params = "saveRows")
	@ResponseBody
	public AjaxJson saveRows(SqlListPage page){
		String message = "操作成功！";
		List<SqlListEntity> lists=page.getSqlListList();
		AjaxJson j = new AjaxJson();
		if(CollectionUtils.isNotEmpty(lists)){
			for(SqlListEntity temp:lists){
				if (StringUtil.isNotEmpty(temp.getId())) {
					SqlListEntity t =this.systemService.get(SqlListEntity.class, temp.getId());
					try {
						MyBeanUtils.copyBeanNotNull2Bean(temp, t);
						sqlListService.updateSqlListEntity(t);
						systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
					} catch (Exception e) {
						e.printStackTrace();
					}
				} else {
					try {
						//temp.setDelFlag(0);若有则需要加
						sqlListService.addSqlListEntity(temp);
						systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
					} catch (Exception e) {
						e.printStackTrace();
					}
					
				}
			}
		}
		return j;
	}
	
    /**
    * 导出excel
    *
    * @param request
    * @param response
    */
    @RequestMapping(params = "exportXlsAll")
    public String exportXlsAll(SqlListEntity sqlList,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid,ModelMap map) {
    	CriteriaQuery cq = new CriteriaQuery(SqlListEntity.class, dataGrid);
    	//查询条件组装器
    	org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, sqlList);
    	try{
    	//自定义追加查询条件
    	}catch (Exception e) {
    		throw new BusinessException(e.getMessage());
    	}
    	cq.add();
    	List<SqlListEntity> list=this.sqlListService.getListByCriteriaQuery(cq, false);
    	List<SqlListPage> pageList=new ArrayList<SqlListPage>();
        if(list!=null&&list.size()>0){
        	for(SqlListEntity entity:list){
        		try{
        		SqlListPage page=new SqlListPage();
        		   MyBeanUtils.copyBeanNotNull2Bean(entity,page);
            	    Object id0 = entity.getId();
				    String hql0 = "from SqlTaskEntity where 1 = 1 AND sqlId = ? ";
        	        List<SqlTaskEntity> sqlTaskEntityList = systemService.findHql(hql0,id0);
            		page.setSqlTaskList(sqlTaskEntityList);
            		pageList.add(page);
            	}catch(Exception e){
            		logger.info(e.getMessage());
            	}
            }
        }
        map.put(NormalExcelConstants.FILE_NAME,"SQL列表");
        map.put(NormalExcelConstants.CLASS,SqlListPage.class);
        map.put(NormalExcelConstants.PARAMS,new ExportParams("SQL列表列表", "导出人:Jeecg","导出信息"));
        map.put(NormalExcelConstants.DATA_LIST,pageList);
        return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}

	/**
	 * 导出excel
	 * @param request
	 * @param response
	 */
    @RequestMapping(params = "exportXls")
    public void exportXls(SqlListEntity sqlList,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid,ModelMap map) throws Exception {
    	CriteriaQuery cq = new CriteriaQuery(SqlListEntity.class, dataGrid);
    	//查询条件组装器
    	org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, sqlList);
    	try{
    		//自定义追加查询条件
			//cq.eq("delFlag",0);
			String sql = SuperQueryUtil.getComplxSuperQuerySQL(request);
			if(oConvertUtils.isNotEmpty(sql)) {
				cq.add(Restrictions.sqlRestriction(" id in ("+sql+")"));
			}
    	}catch (Exception e) {
    		throw new BusinessException(e.getMessage());
    	}
    	cq.add();
    	List<SqlListEntity> list=this.systemService.getListByCriteriaQuery(cq, false);
		Workbook excel=ExcelExportUtil.exportExcel(new ExportParams(), SqlListEntity.class, list);
		response.setContentType("application/x-msdownload;charset=utf-8");
		response.setHeader("Content-disposition", "attachment; filename="+new String("SQL列表列表.xls".getBytes("UTF-8"), "iso-8859-1"));
		OutputStream outputStream = null;
		try {
			outputStream = response.getOutputStream();
			excel.write(outputStream);
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				if(outputStream!=null)outputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
    /**
	 * 通过excel导入数据
	 * @param request
	 * @param
	 * @return
	 */
	@RequestMapping(params = "importExcel", method = RequestMethod.POST)
	@ResponseBody
	public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(2);
			params.setNeedSave(true);
			try {
				List<SqlListEntity> list =  ExcelImportUtil.importExcel(file.getInputStream(), SqlListEntity.class, params);
				for (SqlListEntity page : list) {
		            sqlListService.save(page);
				}
				j.setMsg("文件导入成功！");
			} catch (Exception e) {
				j.setMsg("文件导入失败！");
				logger.error(ExceptionUtil.getExceptionMessage(e));
			}finally{
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return j;
	}
	
	/**
	* 导出excel 使模板
	*/
	@RequestMapping(params = "exportXlsByT")
	public String exportXlsByT(ModelMap map) {
		map.put(NormalExcelConstants.FILE_NAME,"SQL列表");
		map.put(NormalExcelConstants.CLASS,SqlListEntity.class);
		map.put(NormalExcelConstants.PARAMS,new ExportParams("SQL列表列表", "导出人:"+ ResourceUtil.getSessionUser().getRealName(),"导出信息"));
		map.put(NormalExcelConstants.DATA_LIST,new ArrayList());
		return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}
	/**
	* 导入功能跳转
	*
	* @return
	*/
	@RequestMapping(params = "upload")
	public ModelAndView upload(HttpServletRequest req) {
		req.setAttribute("controller_name", "sqlListController");
		return new ModelAndView("common/upload/pub_excel_upload");
	}
	
	/**
	 * 主表导入跳转
	 * @return
	 */
	@RequestMapping(params = "mainUpload")
	public ModelAndView mainUpload(HttpServletRequest req,String listname,String mainId) {
		req.setAttribute("controller_name","sqlListController") ;
		req.setAttribute("method_name","importExcel") ;
		return new ModelAndView("common/upload/mutitables_excel_upload");
	}
	
	/**
	 * 子表导入功能跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "commonUpload")
	public ModelAndView commonUpload(HttpServletRequest req,String listname,String mainId) {
		req.setAttribute("controller_name",listname+"Controller") ;
		req.setAttribute("mainId",mainId);
		return new ModelAndView("common/upload/mutitables_excel_upload");
	}

 	
	
}
